package com.profound.notes.mvvm;

import ohos.aafwk.ability.Ability;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author zjwujlei
 * @date 2021/4/24
 * @email zjwujlei@sina.com
 * @description 可嵌套ViewModel，子ViewModel可以通过{@link #vagueAction(String, Object...)}函数模糊调用所有父ViewModel的action。
 */
public class CompositeViewModel extends AbilityViewModel{

    private ViewModel mParent;

    public CompositeViewModel(Ability ability) {
        super(ability);
    }

    public <VM extends ViewModel> void attach(VM parent){
        mParent = parent;
    }

    public <VM extends ViewModel> VM getParent(Class<VM> clazz) {
        return clazz.cast(mParent);
    }

    public boolean vagueAction(String action,Object... params){
        if(mParent == null){
            return false;
        }
        if(mParent instanceof CompositeViewModel){
            return ((CompositeViewModel) mParent).vagueAction(action,params);
        }else{

            try {
                int len = params.length;
                Class[] parameterTypes = new Class[len];
                for(int i=0;i<len;i++){
                    parameterTypes[i] = params[i].getClass();
                }
                Method method = mParent.getClass().getDeclaredMethod(action,parameterTypes);
                method.setAccessible(true);
                method.invoke(mParent,params);
                return true;
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}
